package com.itmuch.cloud.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.itmuch.cloud.entity.User;
import com.itmuch.cloud.repository.UserRepository;

@RestController
public class UserController {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private UserRepository userRepository;
	
	@GetMapping("/{id}")
	public User findById(@PathVariable Long id) {
		
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		
		LOGGER.info("principal.getClass={}" + principal.getClass());
		LOGGER.info("principal instanceof UserDetails={}", (principal instanceof UserDetails));
		
		if(principal instanceof UserDetails) {
			
			UserDetails user = (UserDetails) principal;
			for(GrantedAuthority auth: user.getAuthorities()) {
				LOGGER.info("username={}, auth={}", user.getUsername(), auth.getAuthority());
			}
			
		} else {
			
		}
		
		User findOne = this.userRepository.findOne(id);
		return findOne;
	}
	
}
